'use strict';

const express = require('express');
const request = require('request');
const path = require('path');
const bodyParser = require('body-parser');
const sha1 = require('sha1');
const util = require("util"); 

const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const accountList = require('./account.js');
const tool = require('./tool.js');

//路径简单，直接在这里配置
var router = express.Router();
//配置端口
var port = process.env.PORT || 10088;

app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/static', express.static('static'));

//在线用户
var onlineClients = {};
//当前在线人数
var onlineCount = 0;
//socket连接
io.on("connection", function(socket){
    let clientId = socket.id;
    console.log('a client {%s} connected',socket.id);
	//监听新用户加入
	socket.on('login', function(obj){
        console.log(obj);
		//检查在线列表，如果不在里面就加入
		if(!onlineClients.hasOwnProperty(socket.id)) {
            var username = obj.username,password = obj.password;
            if(username && accountList.hasOwnProperty(username) && accountList[username] == password){
                let token = sha1(socket.id + '%tail%' + username);
                onlineClients[socket.id] = {
                    name:username,
                    uid:socket.id,
                    token:token
                };
                //在线+1
                onlineCount++;
                console.log('clinet:%s login as %s successed',socket.id,username);
                socket.emit('login success',{id:socket.id,token:token});
            }else{
                socket.emit('login failed','username or password was wrong!');
            }
		}
	});
	
	//监听退出
	socket.on('disconnect', function(){
        console.log('a client {%s} disconnected',socket.id);
		//将退出的用户从在线列表中删除
		if(onlineClients.hasOwnProperty(socket.id)) {
			//删除
			delete onlineClients[socket.id];
			//在线人数-1
			onlineCount --;
		}
        stopTail();
	});
	var spawn = require('child_process').spawn,
        tail = null;
    socket.on('tail',function(obj){
        console.log(obj);
        if(obj && onlineClients.hasOwnProperty(socket.id)){
            console.log('client:%s will tail %s',socket.id,obj.file );
            tail = spawn("tail", ['-f', obj.file]);  
            tail.stdout.on('data',function(data) {  
                //console.log(`stdout: ${data}`);
                socket.emit('tail data',data.toString());
            }); 
            tail.on('close', (code) => {
                console.log(`child process exited with code ${code}`);
            });
            tail.stderr.on('data', (data) => {
                console.log(`stderr: ${data}`);
            });
        }else{
            socket.emit('required login','required login!');
        }
    });
    var stopTail = function(){
        
        if(tail != null){
            tail.kill();
            tail = null;
        }
    };
    socket.on('tail-cancel',function(){
        stopTail();
    });
    setInterval(function(){
        if(onlineClients.hasOwnProperty(socket.id)){
            socket.emit('sys info',tool.systemInfo());
        }
    },2000);

    socket.emit('required login','required login!');
});

http.listen(port,function(){
    console.log('正在监听%d端口',port);
    console.log('current account list:');
    console.log(accountList);
});
app.use(router);
router.get('/',function(req,res){
    res.redirect('/static/');
});

router.get('/status/', function(req, res) {
    res.set('Content-Type', 'text/html;charset=utf-8');
    res.contentType = 'text/html;charset=utf-8';
    let str = util.format("current <strong style=\"color:red;\">%d</strong> client connected!<br/>\n",onlineCount);
    for(var id in onlineClients){
        str += util.format("%s:%s<br>\n",id,onlineClients[id].name);
    }
    res.end(str);
});